package com.iot.iotplus.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.iot.iotplus.entity.Message;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class MsgUtil {

    public static Message getMessage(String jsonString){
        // 使用Fastjson直接解析JSON字符串为JSONObject
        JSONObject jsonObject = JSON.parseObject(jsonString);
        // 获取设备ID
        String device = jsonObject.getString("device");
        // 获取产品密钥
        String productKey = jsonObject.getString("product_key");
        // 获取租户ID
        String tenantId = jsonObject.getString("tenant_id");
        // 将"data"部分转换为Map
        JSONObject data = jsonObject.getJSONObject("data");
        Map dataMap = data.toJavaObject(Map.class);
        return new Message(
                device,
                productKey,
                tenantId,
                new Date(),
                (Integer) dataMap.get("soil_humidity"),
                (Integer) dataMap.get("soil_temperature"),
                (Integer) dataMap.get("soil_ph"),
                (Integer) dataMap.get("soil_npk"),
                Double.parseDouble(dataMap.get("air_temperature").toString()),
                Double.parseDouble(dataMap.get("air_humidity").toString()),
                (Integer) dataMap.get("illumination"),
                (Integer) dataMap.get("co2"),
                (Integer) dataMap.get("ph"),
                (Integer) dataMap.get("wind_speed"),
                (Integer) dataMap.get("flow_velocity")
        );
    }
}
